# -*- coding: utf-8 -*-
from constants import *

import scipy.misc as misc
import numpy as np

filenames = os.listdir(file_dir)

for filename in filenames:    
    x = misc.imread(file_dir+filename,flatten=True)
    x = x.astype(np.int)
	
    # invert colours
    x = 255-x
	
    # set pixels with colour<offset to zero.
    x = (x>offset)*x
   
    # classification number
    f = 1
    
    # Upper left corner
    if(x[0,0]):
        x[0,0] = f
        f += 1
    
    # Upper Edge 
    for i in range(1,x.shape[0]):
        if(x[i,0]):
            if(x[i-1,0]):
                x[i,0] = x[i-1,0]
            else:
                x[i,0] = f
                f +=1
    
    # Side
    for j in range(1,x.shape[1]):
        if(x[0,j]):
            if(x[0,j-1]):
                x[0,j] = x[0,j-1]
            else:
                x[0,j] = f
                f +=1
				
    # pairs is for storing when left and upper cell have different classification        
    pairs = []
    
    # main algorithm
    for i in xrange(1,x.shape[0]):
        for j in xrange(1,x.shape[1]):
            if(x[i,j]):
                if(x[i-1,j]):
                    if(x[i,j-1] and x[i-1,j]!=x[i,j-1]):
                        pairs.append(np.sort((x[i-1,j],x[i,j-1])))
                    x[i,j]=x[i-1,j]
                elif(x[i,j-1]):
                    x[i,j]=x[i,j-1]
                else:
                    x[i,j] = f
                    f+=1
    
    # combine all adjacent numbers created
    pairs = sorted(pairs,key=lambda tup:tup[0])                  
    trans = range(f)
    
    # no replace in normal lists    
    for (i,j) in pairs:
        ri,rj = trans[int(i)],trans[int(j)]
        for t in range(0,f-1):
            if trans[t]==ri:
                trans[t]=rj

    # nice hack; translates values blindingly fast
    key = np.array(trans,dtype=np.int)
    x = key[x].reshape(x.shape)
	
    
    sign_factors = 0
    nums = set(trans[1:])
    for num in nums:
        i = np.sum(x==num)
        if (i> (np.prod(x.shape)*sign_ratio)):
            sign_factors += 1
            
    if sign_factors != 2:
        os.rename(file_dir+filename,target_dir+filename)
        print filename + " -- Invalid --        *moved*"
    else:
        print filename 
    
                     
    
        
    
        
    
